package com.bolt.support.json.dict.internal;

import com.bolt.common.convert.Convert;
import com.bolt.common.reflect.ReflectionUtil;
import com.bolt.common.utils.ArrayUtil;
import com.bolt.common.utils.SpringContextUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.exception.ServiceException;
import com.bolt.support.cache.dict.service.DictCacheService;
import com.bolt.support.json.dict.annotation.DictTranslate;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.util.Objects;

public class DictDataSerializer extends StdSerializer<Object> {


    private transient DictTranslate model;


    public DictDataSerializer(DictTranslate model) {
        super(Object.class);
        this.model = model;
    }

    public void setModel(DictTranslate model) {
        this.model = model;
    }

    public DictTranslate getModel() {
        return model;
    }


    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
        try {
            Object obj = jsonGenerator.getCurrentValue();
            if (model != null) {
                DictCacheService dictCacheService = SpringContextUtil.getBean(DictCacheService.class);
                if (dictCacheService != null && !Objects.isNull(obj)) {
                    String keyValue = Convert.toStr(ReflectionUtil.getFieldValue(obj, model.valueFiled()));
                    Object[] cacheValue = dictCacheService.getCacheData(model.cacheName(), model.dictType(), keyValue);
                    if (ArrayUtil.isNotEmpty(cacheValue)) {
                        jsonGenerator.writeString(Convert.toStr(cacheValue[model.translateIndex()], StrUtil.EMPTY));
                    } else {
                        jsonGenerator.writeString(StrUtil.EMPTY);
                    }
                }
            } else {
                jsonGenerator.writeString(StrUtil.EMPTY);
            }

        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}